﻿using System.Collections.Generic;
using Entitas;
using UnityEngine;

public class SpawnSystem : IExecuteSystem
{
    private readonly IViewService _viewService;

    public SpawnSystem(IViewService viewService)
    {
        _viewService = viewService;
    }
    
    public void Execute()
    {
        var entities = Contexts.sharedInstance.game
            .GetGroup(GameMatcher.Spawn)
            .GetEntities();
        
        TickComponent tick = Contexts.sharedInstance.game.tick;
        float currentTime = tick.tickTime * tick.currentTick;
        foreach (var e in entities)
        {
            SpawnComponent s = e.spawn;
            if (currentTime > s.nextSpawnTime)
            {
                s.nextSpawnTime = currentTime + s.interval;

                Vector3 position = e.transform.position;
        
                var spawner = Contexts.sharedInstance.game.CreateEntity();
                spawner.AddTransform(position, s.destination - position, new SmootherForward(GameDefine.SAMPLES_FOR_SMOOTHING, s.destination - position));
                spawner.AddVelocity(Vector3.zero, 2.0f);
                spawner.AddAccelerate(Vector3.zero, 2.0f);
                spawner.AddColliderRadius(0.3f);
                spawner.AddArriveToDie(s.destination);
                Path path = new Path(
                    new List<Vector3>(
                        new Vector3[] {s.destination}),
                    false);

                spawner.AddBehavior(BehaviorType.FollowPath | BehaviorType.WallAvoidance | BehaviorType.Separation, null, path, Vector3.one);
                _viewService.CreatePlayerView(spawner);

            }
        }
    }
}